package com.wanyangproject.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.TextView;


import com.wanyangproject.R;
import com.wanyangproject.model.AddressModel;
import com.wanyangproject.widget.recyclerview.RecyclerAdapter;
import com.wanyangproject.widget.recyclerview.RecyclerHolder;
import com.wanyangproject.widget.recyclerview.RecyclerListener;

import java.util.List;

public class AddressAdapter extends RecyclerAdapter<AddressModel> implements RecyclerListener.OnClickListener<RecyclerHolder> {

    private TextView addressDef;
    private int addressPos;

    public AddressAdapter(Context context, List<AddressModel> data) {
        super(context, data, R.layout.item_address);
    }

    @Override
    public void convert(RecyclerHolder holder, AddressModel model) {
        TextView addressInfo = holder.findViewById(R.id.address_info);
        TextView addressValue = holder.findViewById(R.id.address_value);
        TextView addressDefault = holder.findViewById(R.id.address_default);
        addressInfo.setText(model.getNick() + "    " + model.getPhone());
        addressValue.setText(model.getAddress());
        setDefault(holder.position, addressDefault, model.isDef());
        holder.setOnClickListener(this, R.id.address_default);
    }

    private void setDefault(int position, TextView textView, boolean isDefault) {
        Drawable checkedDrawable = mContext.getResources().getDrawable(R.mipmap.checked);
        checkedDrawable.setBounds(0, 0, checkedDrawable.getMinimumWidth(), checkedDrawable.getMinimumHeight());
        Drawable uncheckedDrawable = mContext.getResources().getDrawable(R.drawable.unchecked);
        uncheckedDrawable.setBounds(0, 0, uncheckedDrawable.getMinimumWidth(), uncheckedDrawable.getMinimumHeight());
        if (isDefault) {
            addressPos = position;
            addressDef = textView;
            textView.setCompoundDrawables(checkedDrawable, null, null, null);
        } else {
            textView.setCompoundDrawables(uncheckedDrawable, null, null, null);
        }
    }

    @Override
    public void onClick(View v, int position, RecyclerHolder holder) {
        if (addressPos != position && addressDef != null) {
            setDefault(position, addressDef, false);
        }
        TextView address = v.findViewById(R.id.address_default);
        setDefault(position, address, true);
    }
}